package com.project.controller;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.project.model.CityModel;
import com.project.model.EventModel;
import com.project.model.MemberModel;
import com.project.model.NormalDictItem;
import com.project.model.ShippingAddressModel;
import com.project.model.ShopModel;
import com.project.model.SysNoticeModel;
import com.project.model.TradeDetailModel;
import com.project.model.WxUserInfoModel;
import com.project.service.CityService;
import com.project.service.EventService;
import com.project.service.MemberService;
import com.project.service.NormalDictSettingService;
import com.project.service.RedPacketService;
import com.project.service.ShippingAddressService;
import com.project.service.ShopService;
import com.project.service.SysNoticeService;
import com.project.service.TradeDetailService;
import com.project.service.WxUserInfoService;
import com.project.utils.EncryptUtils;
import com.project.utils.QRCodeEncoderHandler;

@Controller
@RequestMapping(value = "/member")
public class MemberController {
	private static Logger logger = LoggerFactory.getLogger(MemberController.class);
	
	@Autowired
	private MemberService memberService;
	
	@Autowired
	private WxUserInfoService wxUserInfoService;
	
	@Autowired
	private CityService cityService;
	
	@Autowired
	private RedPacketService redPacketService;
	
	@Autowired
	private TradeDetailService tradeDetailService;
	
	@Autowired
	private ShopService shopService;
	
	@Autowired
	private EventService eventService;
	
	@Autowired
    private NormalDictSettingService dicService;
	
	@Autowired
	private ShippingAddressService shippingAddressService;
	
	@Autowired
	private SysNoticeService sysNoticeService;
	
	private final String moduleName = "u";
	
	@RequestMapping("index")
	public ModelAndView index(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView();
		HttpSession session = request.getSession();
		MemberModel memberModel = new MemberModel();
		String viewName = "/again_login.jsp";
		if (null != session.getAttribute("userId")) {
			int userId = (int)session.getAttribute("userId");
			memberModel = memberService.getBasisMemberModelById(userId);
			int recommend_member_num = memberService.getRecommendMemberCountById(userId);
			memberModel.setRecommend_member_num(recommend_member_num);
			mav.addObject("member", memberModel);
			
			List<SysNoticeModel> sysNoticeModels = sysNoticeService.listSysNoticeModel();
			
			if (null != sysNoticeModels && sysNoticeModels.size() > 0) {
				mav.addObject("notice", sysNoticeModels.get((sysNoticeModels.size()-1)).getContent());
			} else {
				mav.addObject("notice", "暂无公告");	
			}
			
			
			/*map.put("memberModel", memberModel);
			map.put("code", "1");*/
			viewName = "../user_info.jsp";
		} else {
			// request.getSession().setAttribute("loginPage", "/member/index");
			mav.addObject("page", "/member/index");
		}/* else {
			map.put("code", "-1");
			map.put("msg", "登录失效，请重新登录");
		}*/
		mav.setViewName(viewName);
		return mav;
	}
	
	@RequestMapping("info")
	public ModelAndView info(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView();
		String viewName = "/again_login.jsp";
		
		HttpSession session = request.getSession();
		if (null != session.getAttribute("userId")) {
			int userId = (int)session.getAttribute("userId");
			MemberModel memberModel = memberService.getMemberModelById(userId);
			mav.addObject("member", memberModel);
			viewName = "../user_setting.jsp";
		} else {
			// request.getSession().setAttribute("loginPage", "/member/info");
			mav.addObject("page", "/member/info");
		}
		
		mav.setViewName(viewName);
		return mav;
	}
	
	@RequestMapping("info/name")
	public ModelAndView settingNickName(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView();
		String viewName = "/again_login.jsp";
		
		HttpSession session = request.getSession();
		if (null != session.getAttribute("userId")) {
			mav.addObject("name", request.getParameter("n"));
			viewName = "../../user_setting_nick_name.jsp";
		} else {
			// request.getSession().setAttribute("loginPage", "/member/info/name");
			mav.addObject("page", "/member/info/name");
		}
		
		mav.setViewName(viewName);
		return mav;
	}
	
	@RequestMapping("setName")
	public @ResponseBody Map<String, String> setName(HttpServletRequest request) {
		Map<String, String> map = new HashMap<String, String>();
		HttpSession session = request.getSession();
		if (null == session.getAttribute("userId")) {
			map.put("code", "-1");
			map.put("msg", "登录已失效，请重新登录");
			return map;
		}
		
		int userId = (int)session.getAttribute("userId");
		
		String nick_name = request.getParameter("name");
		
		if (null == nick_name || "".equals(nick_name.trim())) {
			map.put("code", "0");
			map.put("msg", "请输入会员昵称");
			return map;
		}
		
		MemberModel memberModel = new MemberModel();
		memberModel.setId(userId);
		memberModel.setNick_name(nick_name);
		int ret = memberService.getMemberModelByNickNameAndNotId(memberModel);
		if (ret == 0) {
			ret = memberService.updateNickName(memberModel);
			if (ret > 0) {
				map.put("code", "1");
				map.put("msg", "修改会员昵称成功");
			} else {
				map.put("code", "0");
				map.put("msg", "修改会员昵称失败");
			}
		} else {
			map.put("code", "0");
			map.put("msg", "会员昵称已存在");
		}
		return map;
	}
	
	@RequestMapping("info/age")
	public ModelAndView settingAge(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView();
		String viewName = "/again_login.jsp";
		
		HttpSession session = request.getSession();
		if (null != session.getAttribute("userId")) {
			mav.addObject("age", request.getParameter("age"));
			viewName = "../../user_setting_age.jsp";
		} else {
			// request.getSession().setAttribute("loginPage", "/member/info/age");
			mav.addObject("page", "/member/info/age");
		}
		
		mav.setViewName(viewName);
		return mav;
	}
	
	@RequestMapping("setAge")
	public @ResponseBody Map<String, String> setAge(HttpServletRequest request) {
		Map<String, String> map = new HashMap<String, String>();
		HttpSession session = request.getSession();
		if (null == session.getAttribute("userId")) {
			map.put("code", "-1");
			map.put("msg", "登录已失效，请重新登录");
			return map;
		}
		
		int userId = (int)session.getAttribute("userId");
		
		String age_str = request.getParameter("age");
		int age = 0;
		try {
			age = Integer.parseInt(age_str);
		} catch (Exception e) {
			// TODO: handle exception
			map.put("code", "0");
			map.put("msg", "请正确输入年龄");
			return map;
		}
		
		MemberModel memberModel = new MemberModel();
		memberModel.setId(userId);
		memberModel.setAge(age);
		int ret = memberService.updateAge(memberModel);
		if (ret > 0) {
			map.put("code", "1");
			map.put("msg", "修改年龄成功");
		} else {
			map.put("code", "0");
			map.put("msg", "修改年龄失败");
		}
		return map;
	}
	
	
	@RequestMapping("info/education")
	public ModelAndView settingEducation(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView();
		String viewName = "/again_login.jsp";
		
		HttpSession session = request.getSession();
		if (null != session.getAttribute("userId")) {
			NormalDictItem dicItem = new NormalDictItem();
			dicItem.setIntType(5);
			List<NormalDictItem> dicItems = dicService.getDicItemById(dicItem);
			mav.addObject("education", request.getParameter("e"));
			mav.addObject("dicItems", dicItems);
			viewName = "../../user_setting_education.jsp";
		} else {
			// request.getSession().setAttribute("loginPage", "/member/info/education");
			mav.addObject("page", "/member/info/education");
		}
		
		mav.setViewName(viewName);
		return mav;
	}
	
	@RequestMapping("setEducation")
	public @ResponseBody Map<String, String> setEducation(HttpServletRequest request) {
		Map<String, String> map = new HashMap<String, String>();
		HttpSession session = request.getSession();
		if (null == session.getAttribute("userId")) {
			map.put("code", "-1");
			map.put("msg", "登录已失效，请重新登录");
			return map;
		}
		
		int userId = (int)session.getAttribute("userId");
		
		String education_str = request.getParameter("education");
		int education = 0;
		try {
			education = Integer.parseInt(education_str);
		} catch (Exception e) {
			// TODO: handle exception
			map.put("code", "0");
			map.put("msg", "请正确选择学历");
			return map;
		}
		
		MemberModel memberModel = new MemberModel();
		memberModel.setId(userId);
		memberModel.setEducation(education);
		int ret = memberService.updateEducation(memberModel);
		if (ret > 0) {
			map.put("code", "1");
			map.put("msg", "修改学历成功");
		} else {
			map.put("code", "0");
			map.put("msg", "修改学历失败");
		}
		return map;
	}
	
	@RequestMapping("info/salary")
	public ModelAndView settingSalary(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView();
		String viewName = "/again_login.jsp";
		
		HttpSession session = request.getSession();
		if (null != session.getAttribute("userId")) {
			NormalDictItem dicItem = new NormalDictItem();
			dicItem.setIntType(4);
			List<NormalDictItem> dicItems = dicService.getDicItemById(dicItem);
			mav.addObject("salary", request.getParameter("s"));
			mav.addObject("dicItems", dicItems);
			viewName = "../../user_setting_salary.jsp";
		} else {
			// request.getSession().setAttribute("loginPage", "/member/info/salary");
			mav.addObject("page", "/member/info/salary");
		}
		
		mav.setViewName(viewName);
		return mav;
	}
	
	@RequestMapping("setSalary")
	public @ResponseBody Map<String, String> setSalary(HttpServletRequest request) {
		Map<String, String> map = new HashMap<String, String>();
		HttpSession session = request.getSession();
		if (null == session.getAttribute("userId")) {
			map.put("code", "-1");
			map.put("msg", "登录已失效，请重新登录");
			return map;
		}
		
		int userId = (int)session.getAttribute("userId");
		
		String salary_str = request.getParameter("salary");
		int salary = 0;
		try {
			salary = Integer.parseInt(salary_str);
		} catch (Exception e) {
			// TODO: handle exception
			map.put("code", "0");
			map.put("msg", "请正确选择收入情况");
			return map;
		}
		
		MemberModel memberModel = new MemberModel();
		memberModel.setId(userId);
		memberModel.setSalary(salary);
		int ret = memberService.updateSalary(memberModel);
		if (ret > 0) {
			map.put("code", "1");
			map.put("msg", "修改收入情况成功");
		} else {
			map.put("code", "0");
			map.put("msg", "修改收入情况失败");
		}
		return map;
	}
	
	@RequestMapping("setAvatar")
	public @ResponseBody Map<String, String> setAvatar(HttpServletRequest request) {
		Map<String, String> map = new HashMap<String, String>();
		HttpSession session = request.getSession();
		if (null == session.getAttribute("userId")) {
			map.put("code", "-1");
			map.put("msg", "登录已失效，请重新登录");
			return map;
		}
		
		int userId = (int)session.getAttribute("userId");
		
		String avatar = request.getParameter("avatar");
		if (null == avatar || "".equals(avatar.trim())) {
			map.put("code", "0");
			map.put("msg", "请先上传头像");
			return map;
		}
		
		MemberModel memberModel = new MemberModel();
		memberModel.setId(userId);
		memberModel.setAvatar(avatar);
		int ret = memberService.updateAvatar(memberModel);
		if (ret > 0) {
			map.put("code", "1");
			map.put("msg", "修改头像成功");
		} else {
			map.put("code", "0");
			map.put("msg", "修改头像失败");
		}
		return map;
	}
	
	@RequestMapping("setPassword")
	public @ResponseBody Map<String, String> setPassword(HttpServletRequest request) {
		Map<String, String> map = new HashMap<String, String>();
		HttpSession session = request.getSession();
		if (null == session.getAttribute("userId")) {
			map.put("code", "-1");
			map.put("msg", "登录已失效，请重新登录");
			return map;
		}
		int userId = (int)session.getAttribute("userId");
		
		String password = request.getParameter("password");
		if (null == password || "".equals(password.trim())) {
			map.put("code", "-1");
			map.put("msg", "登录密码不能为空");
			return map;
		}
		
		MemberModel memberModel = new MemberModel();
		memberModel.setId(userId);
		memberModel.setPassword(EncryptUtils.encodeMD5String(password));
		int ret = memberService.updatePassword(memberModel);
		if (ret > 0) {
			map.put("code", "0");
			map.put("msg", "修改密码成功");
		} else {
			map.put("code", "-1");
			map.put("msg", "修改密码失败");
		}
		return map;
	}
	
	@RequestMapping("info/myAddress")
	public ModelAndView settingShippingAddress(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView();
		String viewName = "/again_login.jsp";
		
		HttpSession session = request.getSession();
		if (null != session.getAttribute("userId")) {
			List<ShippingAddressModel> listShippingAddress = shippingAddressService.getShippingAddressModelByMemberId(Integer.parseInt(session.getAttribute("userId").toString()));
			if (null == listShippingAddress || listShippingAddress.size() == 0) {
				listShippingAddress = new ArrayList<ShippingAddressModel>();
			}
			mav.addObject("listShippingAddress", listShippingAddress);
			viewName = "../../my_address.jsp";
		} else {
			// request.getSession().setAttribute("loginPage", "/member/info/myAddress");
			mav.addObject("page", "/member/info/myAddress");
		}
		
		mav.setViewName(viewName);
		return mav;
	}
	
	@RequestMapping("income_details")
	public ModelAndView incomeDetails(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView();
		String viewName = "/again_login.jsp";
		
		HttpSession session = request.getSession();
		if (null != session.getAttribute("userId")) {
			int userId = (int)session.getAttribute("userId");
			List<TradeDetailModel> tradeDetails = tradeDetailService.listIndustryModelByMemberId(userId);
			mav.addObject("tradeDetails", tradeDetails);
			viewName = "../income_details.jsp";
		} else {
			// request.getSession().setAttribute("loginPage", "/member/income_details");
			mav.addObject("page", "/member/income_details");
		}
		
		mav.setViewName(viewName);
		return mav;
	}
	
	@RequestMapping("coin_details")
	public ModelAndView coinDetails(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView();
		String viewName = "/again_login.jsp";
		
		HttpSession session = request.getSession();
		if (null != session.getAttribute("userId")) {
			int userId = (int)session.getAttribute("userId");
			MemberModel memberModel = memberService.getMemberModelById(userId);
			mav.addObject("coin_num", memberModel.getCoin_num());
			viewName = "../user_gold.jsp";
		} else {
			// request.getSession().setAttribute("loginPage", "/member/coin_details");
			mav.addObject("page", "/member/coin_details");
		}
		
		mav.setViewName(viewName);
		return mav;
	}
	
	@RequestMapping(moduleName + "/pay_page")
	public ModelAndView payPage(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView();
		if (null == request.getSession().getAttribute("userId")) {
			// request.getSession().setAttribute("loginPage", "/member/"+moduleName+"/pay_page");
			mav.addObject("page", "/member/"+moduleName+"/pay_page");
			mav.setViewName("/again_login.jsp");
			return mav;
		}
		int userid = (int)request.getSession().getAttribute("userId");
		
		MemberModel memberModel = memberService.getMemberModelById(userid);
		if (memberModel.getType() == 1) {
			/*List<ShopModel> shopModels = shopService.getByUserId(userid);
			ShopModel shopModel = new ShopModel();
			if (null != shopModels && shopModels.size() > 0) {
				shopModel = shopModels.get(0);
			}*/
			mav.addObject("memberModel", memberModel);
			mav.setViewName("../../pay.jsp");
		} else {
			mav.addObject("success", 0);
			mav.addObject("msg", "错误！您是店铺会员，不能进行付款操作");
			mav.setViewName("../../pay_info.jsp");
		}
		
		return mav;
	}
	
	@RequestMapping(moduleName + "/scan_pay/{coin_num}")
	public ModelAndView scanPay(@PathVariable("coin_num") double coin_num,HttpServletRequest request) {
		ModelAndView mav = new ModelAndView();
		if (null == request.getSession().getAttribute("userId")) {
			// request.getSession().setAttribute("loginPage", "/member/"+moduleName+"/scan_pay/"+coin_num);
			mav.addObject("page", "/member/"+moduleName+"/scan_pay/"+coin_num);
			mav.setViewName("/again_login.jsp");
			return mav;
		}
		int userid = (int)request.getSession().getAttribute("userId");
		// ShopModel shopModel = shopService.getByUserId(userid);
		// mav.addObject("shopModel", shopModel);
		MemberModel memberModel = memberService.getMemberModelById(userid);
		if (memberModel.getCoin_num() < coin_num) {
			mav.setViewName("/pay_info.jsp");
			mav.addObject("success", 0);
			mav.addObject("msg", "支付失败，您的可用余额不足");
			return mav;
		}
		
		String path = request.getContextPath();
		String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
		
		String logo = basePath+"images/img51.png";
		if (null != memberModel.getAvatar() && !memberModel.getAvatar().equals("")) {
			logo = memberModel.getAvatar();
		}
		
		String url = basePath + "member/u/pay/"+coin_num+"/"+userid;
		String src = QRCodeEncoderHandler.createQRCode(url, 370, "1", logo);
		mav.addObject("src", src);
		mav.addObject("coin_num", coin_num);
		mav.setViewName("../../../scan_pay.jsp");
		return mav;
	}
	
	@RequestMapping(moduleName + "/pay/{coin_num}/{userid}")
	public ModelAndView pay(@PathVariable("coin_num") double coin_num,@PathVariable("userid") int userid,HttpServletRequest request) {
		ModelAndView mav = new ModelAndView();
		if (null == request.getSession().getAttribute("userId")) {
			// request.getSession().setAttribute("loginPage", "/member/"+moduleName+"/pay/"+coin_num+"/"+shop_userid);
			mav.addObject("page", "/member/"+moduleName+"/pay/"+coin_num+"/"+userid);
			mav.setViewName("/again_login.jsp");
			return mav;
		}
		int shop_userid = (int)request.getSession().getAttribute("userId");
		if (shop_userid == userid) {
			mav.addObject("success", 0);
			mav.addObject("msg", "支付失败，您不可以对自己的店铺进行");
			return mav;
		}
		
		// ShopModel shopModel = shopService.getByUserId(shop_userid);
		List<ShopModel> shopModels = shopService.getByUserId(shop_userid);
		ShopModel shopModel = new ShopModel();
		if (null != shopModels && shopModels.size() > 0) {
			shopModel = shopModels.get(0);
		}
		if (null != shopModel) {
			List<EventModel> eventModels = eventService.getListByShopId(shopModel.getId());
			if (null != eventModels && eventModels.size() > 0) {
				EventModel eventModel = null;
				for (int i=0; i<eventModels.size(); i++) {
					if (eventModels.get(i).getStatus() == 3 && eventModels.get(i).getGoodsNum() > eventModels.get(i).getUsedGoodsNum()) {
						eventModel = eventModels.get(i);
						break;
					}
				}
				if (null != eventModel && eventModel.getAmount().doubleValue() > coin_num) {
					if (eventModel.getGoodsAmount().doubleValue() >= coin_num) {
						if (null != shopModel && shopModel.getId() > 0) {
							MemberModel memberModel = memberService.getMemberModelById(userid);
							if (memberModel.getCoin_num() < coin_num) {
								mav.addObject("success", 0);
								mav.addObject("msg", "支付失败，对方的可用余额不足");
							} else {
								// 增加店铺余额，扣除活动商品份数，添加店铺收入记录
								shopModel.setMoney(new BigDecimal(coin_num));
								shopService.updateAddMoney(shopModel);
								eventService.updateUsedGoodsNum(eventModel.getId());
								
								
								TradeDetailModel tradeDetailModel = new TradeDetailModel();
								tradeDetailModel = new TradeDetailModel();
								tradeDetailModel.setMember_id(0);
								tradeDetailModel.setShop_id(shopModel.getId());
								tradeDetailModel.setEvent_id(eventModel.getId());
								tradeDetailModel.setAmount(coin_num);
								tradeDetailModel.setAfter_amount(shopModel.getMoney().doubleValue());
								tradeDetailModel.setType(1); // 用户消费，店铺收入
								tradeDetailService.insert(tradeDetailModel);
								
								// 扣除用户余额，添加用户消费记录
								memberModel.setCoin_num(coin_num);
								memberService.updateCoinNumBySubtract(memberModel);
								memberModel = memberService.getMemberModelById(userid);
								
								tradeDetailModel = new TradeDetailModel();
								tradeDetailModel.setMember_id(userid);
								tradeDetailModel.setShop_id(0);
								tradeDetailModel.setEvent_id(eventModel.getId());
								tradeDetailModel.setAmount(coin_num);
								tradeDetailModel.setAfter_amount(memberModel.getCoin_num());
								tradeDetailModel.setType(2); // 用户消费
								tradeDetailService.insert(tradeDetailModel);
								
								mav.addObject("success", 1);
								mav.addObject("msg", "支付成功");
								mav.addObject("shopName",shopModel.getName());
								DecimalFormat df = new DecimalFormat("#.00");
								mav.addObject("coin_num", df.format(coin_num));
							}
						} else {
							mav.addObject("success", 0);
							mav.addObject("msg", "支付失败，店铺不存在");
						}
					} else {
						mav.addObject("success", 0);
						mav.addObject("msg", "支付失败，每次只能购买一份商品");
					}
				} else {
					mav.addObject("success", 0);
					mav.addObject("msg", "支付失败，店铺活动已结束或不存在");
				}
			} else {
				mav.addObject("success", 0);
				mav.addObject("msg", "支付失败，店铺活动已结束或不存在");
			}
		} else {
			mav.addObject("success", 0);
			mav.addObject("msg", "支付失败，店铺不存在");
		}
		mav.setViewName("/pay_info.jsp");
		return mav;
	}
	
	@RequestMapping(moduleName + "/login")
	public @ResponseBody Map<String, String> login(HttpServletRequest request) {
		String password = request.getParameter("password");
		String phone = request.getParameter("phone");
		String wx_id = request.getParameter("wx_id");
		Map<String, String> map = new HashMap<String, String>();
		
		if (null == phone || "".equals(phone.trim())) {
			map.put("code", "-1");
			map.put("msg", "手机号码不能为空");
			return map;
		} else {
			Pattern p = Pattern.compile("^((13[0-9])|(14[7])|(15[^4,\\D])|(17[0-9])|(18[1-9]))\\d{8}$");
			Matcher m = p.matcher(phone);  
			if (m.matches() == false) {
				map.put("code", "-1");
				map.put("msg", "手机号码有误，请重填");
			}
		}
		
		if (null == password || "".equals(password.trim())) {
			map.put("code", "-1");
			map.put("msg", "登录密码不能为空");
			return map;
		}
		
		if (null == wx_id || "".equals(wx_id)) {
			wx_id = "0";
		}
		
		List<MemberModel> imList = memberService.getMemberModelByPhone(phone.trim());
		if (imList.size() > 0) {
			if(imList.get(0).getPassword().equals(EncryptUtils.encodeMD5String(password))) {
				if (!"0".equals(wx_id) && imList.get(0).getWx_id() == 0) {
					WxUserInfoModel wxUserInfoModel = wxUserInfoService.getWxUserInfoModelById(Integer.parseInt(wx_id));
					if (null != wxUserInfoModel && wxUserInfoModel.getId() > 0) {
						imList.get(0).setWx_id(Integer.parseInt(wx_id));
						if (imList.get(0).getSex() == 0) {
							imList.get(0).setSex(wxUserInfoModel.getSex());
						}
						if (null == imList.get(0).getNick_name() || "".equals(imList.get(0).getNick_name())) {
							imList.get(0).setNick_name(wxUserInfoModel.getNickname());
						}
						if (null == imList.get(0).getAvatar() || "".equals(imList.get(0).getAvatar())) {
							imList.get(0).setAvatar(wxUserInfoModel.getHeadimgurl());
						}
						CityModel cityProvinceModel =  cityService.searchCityCodeByNameAndParentIdAndType(wxUserInfoModel.getProvince(), 0, 1);
						if (null != cityProvinceModel && cityProvinceModel.getId() > 0) {
							if(!imList.get(0).getProvince().equals("000000")) {
								imList.get(0).setProvince(cityProvinceModel.getCode());
							}
							CityModel cityModel =  cityService.searchCityCodeByNameAndParentIdAndType(wxUserInfoModel.getCity(), cityProvinceModel.getId(), 2);
							if (null != cityModel && cityModel.getId() > 0) {
								if(!imList.get(0).getCity().equals("000000")) {
									imList.get(0).setCity(cityModel.getCode());
								}
							}
						}
					}
					memberService.updateWxiInfo(imList.get(0));
				}
				memberService.updateLoginTime(imList.get(0).getId());
				HttpSession session = request.getSession();
				session.setAttribute("userId", imList.get(0).getId());
				map.put("code", "0");
				map.put("msg", "登录成功");
			} else {
				map.put("code", "-1");
				map.put("msg", "密码错误");
			}
		} else {
			map.put("code", "-1");
			map.put("msg", "手机号码不存在");
		}
		return map;
	}

	@RequestMapping(moduleName + "/register")
	public @ResponseBody Map<String, String> register(HttpServletRequest request) {
		String password = request.getParameter("password");
		String phone = request.getParameter("phone");
		String wx_id = request.getParameter("wx_id");
		String code = request.getParameter("code");

		Map<String, String> map = new HashMap<String, String>();
		
		if (null == phone || "".equals(phone.trim())) {
			map.put("code", "-1");
			map.put("msg", "手机号码不能为空");
			return map;
		} else {
			Pattern p = Pattern.compile("^((13[0-9])|(14[7])|(15[^4,\\D])|(17[0-9])|(18[1-9]))\\d{8}$");
			Matcher m = p.matcher(phone);  
			if (m.matches() == false) {
				map.put("code", "-1");
				map.put("msg", "手机号码有误，请重填");
			}
		}
		
		if (null == password || "".equals(password.trim())) {
			map.put("code", "-1");
			map.put("msg", "会员密码不能为空");
			return map;
		}
		
		if (null == code || "".equals(code.trim())) {
			map.put("code", "-1");
			map.put("msg", "短信验证码不能为空");
			return map;
		} else if (null != request.getSession().getAttribute("sms_code") && !"".equals(request.getSession().getAttribute("sms_code"))) {
			String[] sms_code = request.getSession().getAttribute("sms_code").toString().split(",");
			if (sms_code.length == 2) {
				if (!sms_code[0].equals(code) || !sms_code[1].equals(phone)) {
					map.put("code", "-1");
					map.put("msg", "短信验证码错误");
					return map;
				}
			} else {
				map.put("code", "-1");
				map.put("msg", "短信验证码错误");
				return map;
			}
		} else {
			map.put("code", "-1");
			map.put("msg", "短信验证码已失效请重新获取");
			return map;
		}
		
		if (null == wx_id || "".equals(wx_id)) {
			wx_id = "0";
		}

		List<MemberModel> imList = memberService.getMemberModelByPhone(phone.trim());
		logger.info(">>> " + imList);
		if (imList.size() == 0) {
			WxUserInfoModel wxUserInfoModel = null;
			if (!"0".equals(wx_id)) {
				wxUserInfoModel = wxUserInfoService.getWxUserInfoModelById(Integer.parseInt(wx_id));
			}
			//会员不存在，添加
			MemberModel im = new MemberModel();
			im.setPassword(EncryptUtils.encodeMD5String(password));
			im.setCoin_num(0);
			im.setSalary(1);
			if (null != wxUserInfoModel && wxUserInfoModel.getId() > 0) {
				im.setSex(wxUserInfoModel.getSex());
				im.setNick_name(wxUserInfoModel.getNickname());
				im.setAvatar(wxUserInfoModel.getHeadimgurl());
				
				CityModel cityProvinceModel =  cityService.searchCityCodeByNameAndParentIdAndType(wxUserInfoModel.getProvince(), 0, 1);
				if (null != cityProvinceModel && cityProvinceModel.getId() > 0) {
					im.setProvince(cityProvinceModel.getCode());
					CityModel cityModel =  cityService.searchCityCodeByNameAndParentIdAndType(wxUserInfoModel.getCity(), cityProvinceModel.getId(), 2);
					if (null != cityModel && cityModel.getId() > 0) {
						im.setCity(cityModel.getCode());
					} else {
						im.setCity("000000");
					}
				} else {
					im.setProvince("000000");
				}
			} else {
				im.setSex(0);
				im.setProvince("000000");
				im.setCity("000000");
			}
			if (null == im.getNick_name() || "".equals(im.getNick_name())) {
				im.setNick_name(getNickName());
			}
			im.setSearch_num(30);
			im.setArea("000000");
			im.setAge(0);
			im.setEducation(1);
			im.setPhone(phone);
			im.setType(1);
			im.setSearch_num(30);
			im.setWx_id(Integer.parseInt(wx_id));
			
			int ret = memberService.insert(im);
			if (ret > 0) {
				HttpSession session = request.getSession();
				session.setAttribute("userId", im.getId());
				map.put("code", "0");
				map.put("msg", "注册成功");
			} else {
				map.put("code", "-1");
				map.put("msg", "注册失败");
			}
		} else {
			//会员存在，提示
			map.put("code", "-1");
			map.put("msg", "手机号码[" + phone + "]已被注册");
		}
		return map;
	}

	@RequestMapping(moduleName + "/change")
	public @ResponseBody Map<String, String> change(HttpServletRequest request) {
		String password = request.getParameter("password");
		String phone = request.getParameter("phone");
		String code = request.getParameter("code");
		Map<String, String> map = new HashMap<String, String>();
		
		if (null == phone || "".equals(phone.trim())) {
			map.put("code", "-1");
			map.put("msg", "手机号码不能为空");
			return map;
		} else {
			Pattern p = Pattern.compile("^((13[0-9])|(14[7])|(15[^4,\\D])|(17[0-9])|(18[1-9]))\\d{8}$");
			Matcher m = p.matcher(phone);  
			if (m.matches() == false) {
				map.put("code", "-1");
				map.put("msg", "手机号码有误，请重填");
			}
		}
		
		if (null == code || "".equals(code.trim())) {
			map.put("code", "-1");
			map.put("msg", "短信验证码不能为空");
			return map;
		} else if (null != request.getSession().getAttribute("sms_code") && !"".equals(request.getSession().getAttribute("sms_code"))) {
			String[] sms_code = request.getSession().getAttribute("sms_code").toString().split(",");
			if (sms_code.length == 2) {
				if (!sms_code[0].equals(code) || !sms_code[1].equals(phone)) {
					map.put("code", "-1");
					map.put("msg", "短信验证码错误");
					return map;
				}
			} else {
				map.put("code", "-1");
				map.put("msg", "短信验证码错误");
				return map;
			}
		} else {
			map.put("code", "-1");
			map.put("msg", "短信验证码已失效请重新获取");
			return map;
		}
		
		if (null == password || "".equals(password.trim())) {
			map.put("code", "-1");
			map.put("msg", "登录密码不能为空");
			return map;
		}
		
		List<MemberModel> imList = memberService.getMemberModelByPhone(phone.trim());
		if (imList.size() > 0) {
			imList.get(0).setPassword(EncryptUtils.encodeMD5String(password));
			int ret = memberService.updatePassword(imList.get(0));
			if (ret > 0) {
				map.put("code", "0");
				map.put("msg", "修改密码成功");
			} else {
				map.put("code", "-1");
				map.put("msg", "修改密码失败");
			}
		} else {
			map.put("code", "-1");
			map.put("msg", "手机号码不存在");
		}
		return map;
	}
	
	@RequestMapping("gratitude")
	public @ResponseBody Map<String, String> gratitude(HttpServletRequest request) {
		Map<String, String> map = new HashMap<String, String>();
		HttpSession session = request.getSession();
		if (null == session.getAttribute("userId")) {
			map.put("code", "-1");
			map.put("msg", "登录已失效，请重新登录");
			return map;
		}
		
		int userId = (int)session.getAttribute("userId");
		
		String phone = request.getParameter("phone");
		
		if (null == phone || "".equals(phone.trim())) {
			map.put("code", "-1");
			map.put("msg", "手机号码不能为空");
			return map;
		} else {
			Pattern p = Pattern.compile("^((13[0-9])|(14[7])|(15[^4,\\D])|(17[0-9])|(18[1-9]))\\d{8}$");
			Matcher m = p.matcher(phone);  
			if (m.matches() == false) {
				map.put("code", "0");
				map.put("msg", "手机号码有误，请重填");
				return map;
			}
		}
		
		List<MemberModel> memberModels = memberService.getMemberModelByPhone(phone);
		if (null != memberModels && memberModels.size() > 0) {
			if (userId != memberModels.get(0).getId()) {
				MemberModel memberModel = new MemberModel();
				memberModel.setId(userId);
				memberModel.setParent_id(memberModels.get(0).getId());
				int ret = memberService.updatePid(memberModel);
				if (ret > 0) {
					map.put("code", "1");
					map.put("msg", "感恩成功");
				} else {
					map.put("code", "0");
					map.put("msg", "感恩失败");
				}
			} else {
				map.put("code", "0");
				map.put("msg", "不能感恩自己");
			}
		} else {
			map.put("code", "0");
			map.put("msg", "会员不存在");
		}
		return map;
	}
	
	@RequestMapping("logout")
	public ModelAndView logout(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView();
		HttpSession session = request.getSession();
		if (null != session.getAttribute("userId")) {
			session.removeAttribute("userId");
		}
		mav.setViewName("../login.jsp");
		return mav;
	}
	
	private String getNickName() {
		String nickName = "XB"+getFixLenthString(9);
		if (memberService.getMemberModelByNickName(nickName) == 0) {
			return nickName;
		} else {
			return getNickName();
		}
	}
	
	private String getFixLenthString(int strLength) {  
	    Random rm = new Random();  
	    // 获得随机数  
	    double pross = (1 + rm.nextDouble()) * Math.pow(10, strLength);  
	    // 将获得的获得随机数转化为字符串  
	    String fixLenthString = String.valueOf(pross);  
	    // 返回固定的长度的随机数  
	    return fixLenthString.substring(1, strLength + 1);  
	}
}